package com.example.annasbook.writers;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.annasbook.model.BookModel;
import com.example.annasbook.repository.convert.BookConvert;
import com.example.annasbook.repository.entity.BookEntity;
import com.example.annasbook.repository.maper.BookMapper;
import org.springframework.batch.item.support.AbstractItemStreamItemWriter;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

public class BookRedisListWriter extends AbstractItemStreamItemWriter<BookModel> {
    private final BookMapper bookMapper;
    private final BookConvert bookConvert;

    public BookRedisListWriter(BookMapper bookMapper, BookConvert bookConvert) {
        this.bookMapper = bookMapper;
        this.bookConvert = bookConvert;
    }

    @Override
    public void write(List<? extends BookModel> items) {
        Set<String> md5s = items.stream().map(BookModel::getMd5).filter(StringUtils::hasText).collect(Collectors.toSet());
        if (md5s.isEmpty()) {
            return;
        }
        List<BookEntity> bookEntities = bookMapper.selectList(Wrappers.<BookEntity>lambdaQuery().in(BookEntity::getMd5, md5s));
        Map<String, BookEntity> map = bookEntities.stream().collect(Collectors.toMap(BookEntity::getMd5, Function.identity(), (x, y) -> y));

        List<BookEntity> bookSave = new ArrayList<>();
        List<BookEntity> bookUpdate = new ArrayList<>();
        items.forEach(x -> {
            BookEntity book = map.get(x.getMd5());
            if (book == null) {
                BookEntity entity = bookConvert.toBookEntity(x);
                bookSave.add(entity);
                return;
            }
            bookConvert.fillBookEntity(book, x);
            bookUpdate.add(book);
        });
        if (!bookSave.isEmpty()) {
            bookMapper.insertBatchSomeColumn(bookSave);
        }
        if (!bookUpdate.isEmpty()) {
            bookMapper.updateBatch(bookUpdate);
        }
    }
}
